<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="../../lib/layui-v2.5.6/layui/css/layui.css">
</head>
<style>
    .layui-form-label {
        padding-left: 0px;
        width: 60px;
    }

    .layui-form-radio {
        margin-right: 0px;
        padding-right: 5px;
    }
</style>

<body>
    <div class="layui-fluid">
        <div class="layui-row layui-col-space15">
            <div class="layui-col-md7" style="height: 93px;">
                <div class="layui-card">
                    <div class="layui-card-body  " style="height: 58px;">

                        <form id="form" class="layui-form" action="">
                            <div class="layui-form-item">
                                <label class="layui-form-label">车辆选择:</label>
                                <div class="layui-input-inline">
                                    <select id="carSel" lay-filter="carSel" name="quiz1">
                                    </select>
                                </div>

                                <div class="layui-input-inline">
                                    <input type="text" class="layui-input" autocomplete="off" id="startDateTime" />
                                </div>

                                <div class="layui-input-inline" style="width: 10px;padding-top: 5px;">
                                    <span>--</span>
                                </div>

                                <div class="layui-input-inline">
                                    <input type="text" class="layui-input" autocomplete="off" id="endDateTime" />
                                </div>
                                <div class="layui-input-inline" style="margin-left: 20px;">
                                    <button type="button" id="getTrackBtn" class="layui-btn">查找</button>
                                </div>
                            </div>
                        </form>

                    </div>
                </div>
            </div>
            <div class="layui-col-md5">
                <div class="layui-card">
                    <div class="layui-card-body ">
                        <form id="form" class="layui-form" action="">


                            <div class="layui-form-item">

                                <div class="layui-inline">
                                    <label class="layui-form-label">图标尺寸</label>
                                    <div class="layui-input-inline" style="width: 160px;">
                                        <input type="radio" lay-filter="iconRadio" name="iconSize" value="Big" title="大"
                                            checked>
                                        <input type="radio" lay-filter="iconRadio" name="iconSize" value="Middle"
                                            title="中">
                                        <input type="radio" lay-filter="iconRadio" name="iconSize" value="Little"
                                            title="小">
                                    </div>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>

            <div class="layui-col-md12">
                <div class="layui-card">
                    <div class="layui-card-body" style="height: 660px;">
                        <div id="mapDiv" style="height: 100%;"></div>
                    </div>
                </div>
            </div>

        </div>
    </div>
</body>
<script src='../../lib/js/turf.min.js'></script>
<script src="../../lib/layui-v2.5.6/layui/layui.js"></script>


<script type="text/javascript"
    src="https://webapi.amap.com/maps?v=1.4.15&key=eaaf6657a53a8df63c30e059316b6982&plugin=AMap.GraspRoad"></script>

<script>




    layui.use(['form', 'jquery', 'layedit', 'laydate', 'element'], function () {
        form = layui.form;
        $ = layui.$;
        var laydate = layui.laydate;

        laydate.render({
            elem: '#startDateTime' //指定元素
            , type: 'datetime'
            , btns: ['now', 'confirm']
        });
        laydate.render({
            elem: '#endDateTime' //指定元素
            , type: 'datetime'
            , btns: ['now', 'confirm']
        });
        var timerArr = [];
        var pointLinArr = [];
        var pointLinTimeArr = [];

        var map, markersArray = [];
        var markersTimeArray = [];
        var latitude = "";
        var longitude = "";

        var carId = "";
        var startMarkerIcon = "";
        var endMarkerIcon = "";
        var offset = ""

        var isFollowCar = true;
        var isTrackCar = false;
        var polyline = "";
        var marker = "";
        var polylineArr = [];
        var markesToInfoJsonArr = [];
        var pointCount = 490; //轨迹纠错一次最多只能传500个点,该变量控制每段路线的点的数量

        var infoWindow = new AMap.InfoWindow({offset: new AMap.Pixel(0, -30)});

        $(function () {
            getCarList();
            initMap();
            carId = $("#carSel").val();
            getMakerIcon("Big")
            //监听图标尺寸
            form.on('radio(iconRadio)', function (data) {
                getMakerIcon(data.value);
                console.log(markersArray)
                for (var i = 0; i < markersArray.length; i++) {
                    if (i % 2 == 0) {
                        markersArray[i].setIcon(startMarkerIcon)
                    } else {
                        markersArray[i].setIcon(endMarkerIcon)
                    }
                    markersArray[i].setOffset(offset)
                }
            });
        })


        $("#getTrackBtn").click(function () {
            //清空路线数组
            pointLinArr = [];

            //清除地图上已经存在的轨迹线
            map.remove(polylineArr);
            polylineArr = [];

            //清除地图上的标记点
            map.remove(markersArray);
            markersArray = [];

            pointInfoWindowIndex = 0;//起点终点的信息框的索引
            pointInfoWindowArr = [];


            for (var i = 0; i < markesToInfoJsonArr.length; i++) {
                markesToInfoJsonArr[i].info.close();
            }

            markersTimeArray = [];

            turfPointArr = [];
            markesToInfoJsonArr = [];

            //获取所有路线
            getTrack($("#carSel").val(), $("#startDateTime").val(), $("#endDateTime").val())
            console.log(pointLinArr)
            //遍历路线集合,对每条路线进行绘线
            for (var i = 0; i < pointLinArr.length; i++) {
                var graspRoad = new AMap.GraspRoad()
                arrLine = pointLinArr[i]
                //纠正接口一次只能传500个点,所以对于长线需要分段
                var j = (arrLine.length % pointCount == 0 ? parseInt(arrLine.length / pointCount) : parseInt(arrLine.length / pointCount + 1));
                for (var k = 0; k < j; k++) {
                    arrNew = arrLine.slice(pointCount * k, pointCount * k + pointCount)
                    if (k != 0) {
                        arrNew.unshift(arrLine[k * pointCount - 1])
                    }
                    console.log(arrNew)
                    getGraspRoad(arrNew,k,j,i)
                }
            }       
        });

        //画出轨迹线的同步方法
        async function getGraspRoad(arrNew,k,j,i){
            var graspRoad = new AMap.GraspRoad();
            await graspRoad.driving(arrNew, function (error, result) {
                        console.log(error)
                        if (!error) {
                            var path2 = [];
                            var newPath = result.data.points;
                            for (var s = 0; s < newPath.length; s++) {
                                path2.push([newPath[s].x, newPath[s].y])
                            }
                            var newLine = new AMap.Polyline({
                                path: path2,
                                strokeWeight: 8,
                                strokeOpacity: 0.8,
                                strokeColor: '#0091ea',
                                showDir: true,
                                lineJoin: 'round',
                                lineCap: 'round', // 折线拐点连接处样式
                            })
                            map.add(newLine)
                            polylineArr.push(newLine)
                            if(k == 0){
                                //生成本条路线的起点
                                var startPoint = new AMap.LngLat(path2[0].lng,path2[0].lat)
                             
                                var startMarker = new AMap.Marker({
                                    icon: startMarkerIcon,
                                    position:startPoint,
                                    offset: offset
                                });
                                startMarker.setMap(map);
                                markersArray.push(startMarker)

                                startMarker.content = dateToString(new Date(pointLinTimeArr[i][0]));
                                startMarker.on('click', markerClick);
                                //startMarker.emit('click', {arr:"ff",target: startMarker});
                            }
                            if(k == j-1){
                                var endPoint = new AMap.LngLat(path2[path2.length-1].lng,path2[path2.length-1].lat)
                                //生成本条路线的终点
                                var endMarker = new AMap.Marker({
                                    icon: endMarkerIcon,
                                    position: endPoint,
                                    offset: offset
                                });
                                endMarker.setMap(map);
                                markersArray.push(endMarker)
                                map.setFitView(); 
                                
                                endMarker.content = dateToString(new Date(pointLinTimeArr[i][pointLinTimeArr[i].length-1]));
                                endMarker.on('click', markerClick);
                                //endMarker.emit('click', {arr:"ff",target: startMarker});
                            }
                        }
                    })
        }


        function markerClick(e) {
            infoWindow.setContent(e.target.content);
            infoWindow.open(map, e.target.getPosition());
        }

        //地图初始化
        function initMap() {

            map = new AMap.Map('mapDiv', {
                zoom: 11,//级别
                center: [123.435, 41.6986],//中心点坐标
                resizeEnable: true //是否监控地图容器尺寸变化
            });
        }

        //获取车辆列表
        function getCarList() {
            $.ajax({
                url: "https://device-dev.horus.net.cn/api/vehicle/getVehicle",
                data: {
                    "Authorization": "eyJhbGciOiJIUzUxMiJ9.eyJ1aWQiOjIsImFwcElkIjoiaG9ydXMiLCJyb2xlTGlzdFN0ciI6IiIsImV4cCI6NDcxNzk2NjgzNn0.r1G1EaNV2dPraRooct5TtsQ8gSIRcR7kL49xQzpL8BtPWeZOGgaTgO8xZS4xzWKY9rppuZV0eko84Jb2RAmPNQ"
                },
                type: "get",
                async: false,
                success: function (res) {
                    carList = res.content;
                    var opt = "";
                    for (var i = 0; i < carList.length; i++) {
                        opt += "<option value='" + carList[i].id + "'";
                        if (i == 0) {
                            opt += "selected "
                        }
                        opt += " >" + carList[i].number + "</option>";
                    }
                    $("#carSel").html(opt);
                    form.render('select')
                }
            })
        }

        //获取历史轨迹
        function getTrack(carId, startDateTime, endDateTime) {
            $.ajax({
                url: "https://device-dev.horus.net.cn/api/vehicle/getPosition",
                data: {
                    "Authorization": "eyJhbGciOiJIUzUxMiJ9.eyJ1aWQiOjIsImFwcElkIjoiaG9ydXMiLCJyb2xlTGlzdFN0ciI6IiIsImV4cCI6NDcxNzk2NjgzNn0.r1G1EaNV2dPraRooct5TtsQ8gSIRcR7kL49xQzpL8BtPWeZOGgaTgO8xZS4xzWKY9rppuZV0eko84Jb2RAmPNQ",
                    "vid": carId,
                    "begin": startDateTime,
                    "end": endDateTime
                },
                type: "get",
                async: false,
                success: function (res) {
                    var track = res.content;
                    var newPath = [];
                    var newPathTime = [];
                    console.log(track)
                    for (var i = 0; i < track.length; i++) {
                        //var newLaLng = new AMap.LngLat(track[i].longitude,track[i].latitude)
                        var x = track[i].longitude;
                        var y = track[i].latitude;
                        var tm = "";
                        var ag = "";
                        var sp = "";
                        if (i == 0) {
                            tm = track[i].timestamp / 1000
                            ag = 0
                            sp = 0
                        } else {
                            tm = (track[i].timestamp - track[i - 1].timestamp) / 1000;
                            if (tm == 0) {
                                sp = 0
                            } else {
                                sp = getV(track[i - 1].longitude, track[i - 1].latitude, track[i].longitude, track[i].latitude, tm)

                            }

                            ag = getAngle(track[i - 1].longitude, track[i - 1].latitude, track[i].longitude, track[i].latitude)
                        }
                        var originPathJson = { "x": x, "y": y, "sp": sp, "ag": ag, "tm": tm }
                        newPath.push(originPathJson);
                        newPathTime.push(track[i].timestamp);
                        if (i == 1630) {
                            console.log(i)
                        }

                        if (i == track.length - 1) {
                            pointLinArr.push(newPath);
                            pointLinTimeArr.push(newPathTime);
                            break;
                        }
                        //比较两个点之间的时间差,大于规定时间则重新生成一段轨迹
                        if ((track[i + 1].timestamp - track[i].timestamp) > (300 * 1000)) {
                            pointLinArr.push(newPath);
                            pointLinTimeArr.push(newPathTime);
                            newPath = [];
                            newPathTime = [];
                        }
                    }
                    console.log(pointLinTimeArr)

                }
            })

        }




        //根据车辆id获取最后坐标点
        function getLastLocationByCarId(carId) {
            $.ajax({
                url: "https://device-dev.horus.net.cn/api/vehicle/getLastPosition",
                data: {
                    "Authorization": "eyJhbGciOiJIUzUxMiJ9.eyJ1aWQiOjIsImFwcElkIjoiaG9ydXMiLCJyb2xlTGlzdFN0ciI6IiIsImV4cCI6NDcxNzk2NjgzNn0.r1G1EaNV2dPraRooct5TtsQ8gSIRcR7kL49xQzpL8BtPWeZOGgaTgO8xZS4xzWKY9rppuZV0eko84Jb2RAmPNQ",
                    "vid": carId
                },
                type: "get",
                async: false,
                success: function (res) {
                    latitude = res.content.latitude;
                    longitude = res.content.longitude;
                }
            })
        }


        //车辆图标
        function getMakerIcon(iconName) {
            var size = "";
            if (iconName == "Big") {
                size = new AMap.Size(64, 64);//图片大小
                offset = new AMap.Pixel(-32, -64)
            } else if (iconName == "Middle") {
                size = new AMap.Size(48, 48);//图片大小
                offset = new AMap.Pixel(-24, -48)
            } else if (iconName == "Little") {
                size = new AMap.Size(32, 32);//图片大小
                offset = new AMap.Pixel(-16, -32)
            }
            startMarkerIcon = new AMap.Icon({
                // 图标尺寸
                size: size,
                // 图标的取图地址
                image: "../../lib/image/startPoint" + iconName + ".png",
                imgageSze: size
            });
            endMarkerIcon = new AMap.Icon({
                // 图标尺寸
                size: size,
                // 图标的取图地址
                image: "../../lib/image/endPoint" + iconName + ".png",
                imgageSze: size
            });
        }


        function dateToString(date) {
            var year = date.getFullYear();
            var month = (date.getMonth() + 1).toString();
            var day = (date.getDate()).toString();
            var hour = (date.getHours()).toString();
            var min = (date.getMinutes()).toString();
            var sec = (date.getSeconds()).toString();
            if (month.length == 1) {
                month = "0" + month;
            }
            if (day.length == 1) {
                day = "0" + day;
            }
            var dateTime = year + "-" + month + "-" + day + " " + hour + ":" + min + ":" + sec;
            return dateTime;
        }

        //已知两点获取角度
        function getAngle(lng_a, lat_a, lng_b, lat_b) {
            var a = (90 - lat_b) * Math.PI / 180;
            var b = (90 - lat_a) * Math.PI / 180;
            var AOC_BOC = (lng_b - lng_a) * Math.PI / 180;
            var cosc = Math.cos(a) * Math.cos(b) + Math.sin(a) * Math.sin(b) * Math.cos(AOC_BOC);
            var sinc = Math.sqrt(1 - cosc * cosc);
            var sinA = Math.sin(a) * Math.sin(AOC_BOC) / sinc;
            var A = Math.asin(sinA) * 180 / Math.PI;
            var res = 0;
            if (lng_b > lng_a && lat_b > lat_a) res = A;
            else if (lng_b > lng_a && lat_b < lat_a) res = 180 - A;
            else if (lng_b < lng_a && lat_b < lat_a) res = 180 - A;
            else if (lng_b < lng_a && lat_b > lat_a) res = 360 + A;
            else if (lng_b > lng_a && lat_b == lat_a) res = 90;
            else if (lng_b < lng_a && lat_b == lat_a) res = 270;
            else if (lng_b == lng_a && lat_b > lat_a) res = 0;
            else if (lng_b == lng_a && lat_b < lat_a) res = 180;

            return res;
        }
        //已知两点和时间间隔获取速度
        function getV(lng1, lat1, lng2, lat2, tm) {
            var radLat1 = lat1 * Math.PI / 180.0;
            var radLat2 = lat2 * Math.PI / 180.0;
            var a = radLat1 - radLat2;
            var b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0;
            var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
                Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
            s = s * 6378.137;// EARTH_RADIUS;
            s = Math.round(s * 10000) / 10;
            var v = s / tm;
            return v;
        }

    })


</script>

</html>